﻿using JwtDemo.AppSettingConfig;
using JwtDemo.Consts;
using JwtDemo.Interface;
using JwtDemo.Models;
using JwtDemo.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;

namespace JwtDemo.Controllers
{
    public class UserController : Controller
    {
        protected readonly IUserContextBase _user ;
        private readonly CacheService _cache ;
        private readonly IConfiguration _config ;

       
        public UserController(IUserContext user, CacheService cache, IConfiguration config)
        {
            _user = user;
            _cache = cache;
            _config = config;
        }

        public IActionResult LoginPage()
        {
            return View();
        }

        /// <summary>
        /// 登录获取Token ✅
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        //[HttpPost("login")]
        [AllowAnonymous]
        public async Task<ActionResult<LoginResult>> LoginAsync(LoginDto dto)
        {

            //Guid id = Guid.NewGuid();
            //string userid = id.ToString();
            Guid id = Guid.Parse("2d9bf6f5-a415-46d5-822b-7e9a7bee717b");

            // 查询用户
            //User? user = await manager.Query.Db.Where(u => u.UserName.Equals(dto.UserName))
            //    .FirstOrDefaultAsync();
            //if (user == null)
            //{
            //    return NotFound("不存在该用户");
            //}

            User ? user = new User() { UserName="test user", Id= id };

            // 可将 dto.VerifyCode 设置为必填，以强制验证
            if (dto.VerifyCode != null)
            {
                var key = AppConst.VerifyCodeCachePrefix + user.Email;
                var cacheCode = _cache.GetValue<string>(key);
                if (cacheCode == null)
                {
                    return BadRequest("验证码已过期");
                }
                if (!cacheCode.Equals(dto.VerifyCode))
                {
                    return BadRequest("验证码错误");
                }
            }
            //密码校验通过
            //if (HashCrypto.Validate(dto.Password, user.PasswordSalt, user.PasswordHash))
            {
                // 获取Jwt配置
                JwtOption jwtOption = _config.GetSection("Authentication:Jwt").Get<JwtOption>()
                    ?? throw new ArgumentNullException("未找到Jwt选项!");
                var sign = jwtOption.Sign;
                var issuer = jwtOption.ValidIssuer;
                var audience = jwtOption.ValidAudiences;

                // 构建返回内容
                if (!string.IsNullOrWhiteSpace(sign) &&
                    !string.IsNullOrWhiteSpace(issuer) &&
                    !string.IsNullOrWhiteSpace(audience))
                {
                    // 设置角色或用户等级以区分权限
                    var roles = new List<string> { AppConst.User };
                    // 过期时间:minutes
                    var expired = 60 * 24;
                    JwtService jwt = new(sign, audience, issuer)
                    {
                        TokenExpires = expired,
                    };
                    // 添加管理员用户标识
                    if (!roles.Contains(AppConst.User))
                    {
                        roles.Add(AppConst.User);
                    }
                    jwt.Claims = new List<Claim>() { new Claim(ClaimTypes.Name, user.UserName) };

                    string token = jwt.GetToken(user.Id.ToString(), roles);
                    string key = AppConst.LoginCachePrefix + user.Id.ToString();
                    // 缓存登录状态  Microsoft.Extensions.Caching.Distributed.IDistributedCache
                    await _cache.SetValueAsync(key, true, expired * 60);
                    var val = _cache.GetValue<bool>(key);

                    return new LoginResult
                    {
                        Id = user.Id,
                        Roles = roles,
                        Token = token,
                        Username = user.UserName
                    };
                }
                else
                {
                    throw new Exception("缺少Jwt配置内容");
                }
            }
            //else
            //{
            //    return Problem("用户名或密码错误", title: "");
            //}
        }

        /// <summary>
        /// 退出 ✅
        /// </summary>
        /// <returns></returns>
        [HttpPut("logout/{id}")]
        public async Task<ActionResult<bool>> LogoutAsync([FromRoute] Guid id)
        {
            //if (await manager.ExistAsync(id))
            {
                // 清除缓存状态
                await _cache.RemoveAsync(AppConst.LoginCachePrefix + id.ToString());
                return Ok();
            }
            return NotFound();
        }

    }
}
